<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="业务类型" prop="auditBusinessType">
        <el-select v-model="queryParams.auditBusinessType" placeholder="请选择审核业务类型" clearable>
          <el-option
            v-for="dict in dict.type.audit_business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="业务类型" align="center" prop="auditBusinessType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_business_type" :value="scope.row && scope.row.auditBusinessType"/>
        </template>
      </el-table-column>
      <el-table-column label="发起时间" align="center" prop="startDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发起人" align="center" prop="endDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <template
            v-if="scope.row.auditStatus === '0' && scope.row.currentAuditRouteId !== null && scope.row.actionType ==='1'">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAudit(scope.row, true)"
              v-hasPermi="['system:record:add']"
            >审核
            </el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleAudit(scope.row, false)"
              v-hasPermi="['system:record:add']"
            >详情
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核弹框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form :model="currentLeave" label-width="80px" :disabled="true">
        <!-- 新增 el-row 包裹 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="业务类型" prop="auditBusinessType">
              <el-select v-model="currentLeave.auditBusinessType" placeholder="请选择业务类型">
                <el-option
                  v-for="dict in dict.type.audit_business_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startDatetime">
              <el-date-picker clearable
                              v-model="currentLeave.startDatetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endDatetime">
              <el-date-picker clearable
                              v-model="currentLeave.endDatetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form v-if="dialogEditable" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核结果" prop="auditResult">
              <el-radio-group v-model="form.auditResult" @change="handleAuditResultChange">
                <el-radio
                  v-for="dict in dict.type.audit_result"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驳回路径" prop="rollbackRouteId" v-if="needRollback">
              <el-select
                v-model="form.rollbackRouteId"
                placeholder="请选择驳回到的节点"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in rollbackOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="不通过原因" prop="nopassReason" v-if="needReason">
          <el-input
            type="textarea"
            v-model="form.nopassReason"
            placeholder="请输入不通过原因"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注（选填）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template v-if="currentLeave && currentLeave.leaveId">
        <el-divider content-position="left">审核信息</el-divider>
        <audit-info-table
          :data="auditInfo"
          :node-mode-options="dict.type.audit_mode"
          :audit-status-options="dict.type.audit_status"
          :audit-result-options="dict.type.audit_result"
          :format-fallback="formatAssignees"
          :show-round="false"
          :show-order="false"
          :show-copy-info="true"
          :role-fields="['auditRoleName', 'auditRoleId']"
        />
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="dialogEditable"
          type="primary"
          @click="submitAudit"
        >提 交
        </el-button>
        <el-button @click="cancel">{{ dialogEditable ? '取 消' : '关 闭' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {auditAssigneeList} from "@/api/system/auditAssignee"
import {getLeave} from "@/api/system/leave"
import {createAuditRecord} from "@/api/system/auditRecord"
import {getRollbackOptions} from "@/api/system/auditRoute"
import AuditInfoTable from "@/components/AuditInfoTable"

export default {
  name: "LeaveToApprove",
  dicts: ['audit_business_type', 'audit_status', 'audit_mode', 'audit_result'],
  components: {
    AuditInfoTable
  },
  computed: {
    currentUserId() {
      return this.$store.getters.id
    },
    needReason() {
      if (!this.form.auditResult) return false
      return this.rejectAuditValues.has(this.form.auditResult)
    },
    needRollback() {
      if (!this.form.auditResult) return false
      return this.rollbackAuditValues.has(this.form.auditResult)
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 待审核请假表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditBusinessType: null,
        auditStatus: null
      },
      // 表单参数
      form: {
        auditRecordId: null,
        auditRouteId: null,
        businessId: null,
        auditBusinessType: null,
        auditAssigneeId: null,
        userId: null,
        auditResult: null,
        nopassReason: '',
        rollbackRouteId: null,
        remark: ''
      },
      // 审核信息
      auditInfo: [],
      // 当前请假单详情
      currentLeave: {},
      rejectAuditValues: new Set(),
      rollbackAuditValues: new Set(),
      rollbackOptions: [],
      dialogEditable: true,
      // 表单校验
      rules: {
        auditResult: [
          {required: true, message: "请选择审核结果", trigger: "change"}
        ],
        nopassReason: [
          {required: true, message: "请输入不通过原因", trigger: "blur"}
        ],
        rollbackRouteId: [
          {required: true, message: "请选择驳回路径", trigger: "change"}
        ]
      }
    }
  },
  created() {
    this.initRejectAuditValues()
    this.getList()
  },
  methods: {
    /** 查询请假列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        userId: this.currentUserId
      }
      auditAssigneeList(params).then(response => {
        this.leaveList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        auditRecordId: null,
        auditRouteId: null,
        businessId: null,
        auditBusinessType: null,
        auditAssigneeId: null,
        userId: null,
        auditResult: null,
        nopassReason: '',
        rollbackRouteId: null,
        remark: ''
      }
      this.resetForm("form")
      this.auditInfo = []
      this.currentLeave = {}
      this.rollbackOptions = []
      this.dialogEditable = true
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaveId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 审核操作 */
    handleAudit(row, isEditable) {
      this.reset()
      if (!row || !row.businessId) {
        this.$modal.msgError("未找到业务单信息")
        return
      }
      this.initRejectAuditValues()
      this.form = {
        auditRecordId: null,
        auditRouteId: row.auditRouteId || null,
        businessId: row.businessId || null,
        auditBusinessType: row.auditBusinessType || null,
        auditAssigneeId: row.auditAssigneeId || null,
        userId: this.currentUserId,
        auditResult: null,
        nopassReason: '',
        rollbackRouteId: null,
        remark: ''
      }
      getLeave(row.businessId).then(response => {
        const resData = response.data || {}
        this.auditInfo = Array.isArray(resData.auditInfo) ? resData.auditInfo : []
        this.currentLeave = resData
        this.dialogEditable = isEditable
        this.open = true
        this.title = isEditable ? "审核请假申请" : "查看审核详情"
        this.loadRollbackOptions()
      })
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = {
            ...this.form,
            auditResult: this.form.auditResult,
            nopassReason: this.needReason ? this.form.nopassReason : '',
            rollbackRouteId: this.needRollback ? this.form.rollbackRouteId : null,
            userId: this.currentUserId
          }
          createAuditRecord(payload).then(() => {
            this.$modal.msgSuccess("审核成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 格式化审核人员列表 */
    formatAssignees(list) {
      if (!Array.isArray(list) || list.length === 0) {
        return '-'
      }
      const names = list
        .map(item => item && (item.userName || item.userId))
        .filter(item => item !== undefined && item !== null && item !== '')
      return names.length ? names.join('、') : '-'
    },
    /** 初始化需要填写原因的审核结果 */
    initRejectAuditValues() {
      const dicts = this.dict?.type?.audit_result || []
      const targets = dicts.filter(item => item.label && (item.label.includes('拒') || item.label.includes('驳')))
      this.rejectAuditValues = new Set(targets.map(item => item.value))
      const rollbackTargets = dicts.filter(item => item.label && item.label.includes('驳'))
      this.rollbackAuditValues = new Set(rollbackTargets.map(item => item.value))
    },
    handleAuditResultChange(value) {
      if (!this.rejectAuditValues.has(value)) {
        this.form.nopassReason = ''
      }
      if (!this.rollbackAuditValues.has(value)) {
        this.form.rollbackRouteId = null
        this.rollbackOptions = []
      } else {
        this.loadRollbackOptions()
      }
    },
    loadRollbackOptions() {
      const { auditRouteId, businessId, auditBusinessType } = this.form
      if (!auditRouteId || !businessId || !auditBusinessType) {
        this.rollbackOptions = []
        return
      }
      getRollbackOptions({
        businessId,
        auditBusinessType,
        currentRouteId: auditRouteId
      }).then(response => {
        const list = Array.isArray(response.data) ? response.data : []
        this.rollbackOptions = list.map(item => {
          const orderLabel = item?.auditOrder != null ? `节点${item.auditOrder}` : '节点'
          const roleLabel = item?.auditRoleName || item?.auditRoleId || item?.auditRouteId || ''
          return {
            label: roleLabel ? `${orderLabel} - ${roleLabel}` : orderLabel,
            value: item?.auditRouteId
          }
        })
      })
    },
    /** 校验不通过原因 */
    validateReason(value, callback) {
      if (this.needReason && (!value || !value.trim())) {
        callback(new Error('请输入不通过原因'))
      } else {
        callback()
      }
    },
    /** 校验驳回路径 */
    validateRollback(value, callback) {
      if (this.needRollback) {
        if (value === undefined || value === null || value === '') {
          callback(new Error('请选择驳回路径'))
          return
        }
      }
      callback()
    }
  }
}
</script>
